<?php

require_once(DIR_LIB."VsGui".DIR_SEP."vssmartywidget.php");

require_once(DIR_LIB."Junona".DIR_SEP."junobjectsfactory.php");

class XCartModels extends VsSmartyWidget {

	function __construct(&$page, $pager=NULL) {
		// Ne go zabravqj ina4e nqma $smarty Object
		parent::__construct();

		$this->_template = dirname(__FILE__).DIR_SEP."xcart_models.html";

		$this->_wwwDir = 'templates/XCart/';
		$this->assign('wwwDir', $this->_wwwDir);

		$page->addJsFile("js/jquery-1.7.2.min.js");
		$page->addJsFile("js/jquery-ui-1.8.22.custom.min.js");
		$page->addCssFile("css/ui-lightness/jquery-ui-1.8.22.custom.css");
		
		
		$page->addJsCode($this->jsfuncRadioValue());


		if(isset($_POST['sub_model'])) {
			$this->procForm();
		}

		if(isset($_POST['change_names'])) {
			$this->procFormChangeNames();
		}

		if(isset($_POST['del_models'])) {
			$this->procFormDelete();
		}
		
		$pager = new VsPager($page, JunObjectsFactory::countModels(), 30);
		$models = JunObjectsFactory::makeModels($pager);
		$this->assign('listModels', $models);

		if(isset($_REQUEST['opid']))
			$this->assign('operator', JunObjectsFactory::makeOperator($_REQUEST['opid']));

		if($pager)
			$this->assign('pager', $pager->show());
		else
			$this->assign('pager', '');

	}
	//============================================================================

	function show() {

		return $this->fetch($this->_template);
	}
	//============================================================================

	private function procForm() {
		$model = JunModel::makeFromForm($_POST);
		$model->save();

		header("Location: ".$_SERVER['PHP_SELF']);		// .$SERVER['HTTP_HOST']."/"
	}
	//===========================================================================

	private function procFormChangeNames() {
		foreach($_POST['modids'] as $id=>$value) {
			JunModel::updateNames($id, $_POST['posted_data'][$id]['number'], $_POST['posted_data'][$id]['name']);
		}

		header("Location: ".$_SERVER['PHP_SELF']);		// .$SERVER['HTTP_HOST']."/"
	}
	//===========================================================================

	private function procFormDelete() {
		//echo "EHO"; exit;
		foreach($_POST['modids'] as $id=>$value) {
			JunModel::remove($id);
		}

		//exit;
		header("Location: ".$_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING']);
	}
	//===========================================================================

	private function jsfuncRadioValue() {
		$js = "function radioValue(radio) {";
		$js .= "	for (var i=0; i < radio.length; i++) {";
		$js .= "		if (radio[i].checked)";
		$js .= "			return radio[i].value;";
		$js .= "	}";
		$js .= "}";

		return $js;
	}
	//===========================================================================

};

?>
